package com.tucanstubs.android_wheresmystuff.activities;


import java.text.ParseException;

import com.tucanstubs.android_wheresmystuff.R;
import com.tucanstubs.android_wheresmystuff.login.Login;
import com.tucanstubs.android_wheresmystuff.login.LoginException;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.*;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Bundle;

/**
 * Activity used for logging users into the application. 
 * Also handles the creation of new user accounts and users forgetting
 * their login information. 
 * 
 * @author team 37
 * @version 2.0 4/9/2013
 *
 */
public class LoginPageActivity extends Activity{
	
	private EditText userName, password;
	
	/**
	 * Creates the Activity. Sets up all GUI components. 
	 * @param SavedInstanceState not used
	 */
	public void onCreate(Bundle SavedInstanceState){
		super.onCreate(SavedInstanceState);
		setContentView(R.layout.login_screen);
		userName = (EditText) findViewById(R.id.User_Name);
		password = (EditText) findViewById(R.id.Input_Password);
		try {
			Login.addDB(this);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * Method that is called when a button is clicked. User can either attempt to login, create a new account, or 
	 * click that they forgot their user name or password. 
	 * 
	 * @param view The Button which was clicked on
	 */
	public void onClick(View view) {
		Intent nextIntent;
		switch (view.getId()) {
		case R.id.Log_In:
			//attempt login
			boolean authenticated = false;
			Toast toast; 
			
			try {
				
				authenticated = Login.authenticateUser(this,userName.getText().toString(), password.getText().toString());
			} catch (NullPointerException e){
				
				toast = Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			} catch (LoginException e) {
				
				toast = Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			} catch (Exception e) {
				
				toast = Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}
			if(authenticated){
				Log.i(Tags.LOGINPAGEACTIVITY,"Login Success");					
				nextIntent = new Intent(this,HomeScreenActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(Tags.USERNAME,userName.getText().toString());
				nextIntent.putExtras(bundle);
				startActivity(nextIntent);
				finish();
			}
			break;
		//pass control to sign up screen
		case R.id.Sign_Up:
			Log.i(Tags.LOGINPAGEACTIVITY,"Sign UP clicked");
			nextIntent = new Intent(this,SignUpScreenActivity.class);
			startActivity(nextIntent);
			break;
		}		
	}
}	
